const {
    createMoment,
    getMomentList,
    getMomentById,
    updateMoment,
    removeMoment,
    addLabel
} = require('../service/moment.service')
const { hasLabel } = require('../service/label.service')
const { getFileByName } = require('../service/file.service')
const { PICTURE_PATH } = require('../constans/file-path')
const fs = require('fs');

class MomentController {
    async create(ctx, next) {
        // 1.获取数据(user_id, content)
        const userId = ctx.user.id;
        const content = ctx.request.body.content;
        // 2.将数据插入到数据库
        const result = await createMoment(content, userId);
        ctx.body = result
    }
    async list(ctx, next) {
        const { offset, size } = ctx.query
        // 2.查询列表
        const result = await getMomentList(offset, size);
        ctx.body = result;
    }
    async detail(ctx, next) {
        const { momentId } = ctx.params
        // 2.根据id去查询这条数据
        const result = await getMomentById(momentId);
        ctx.body = result;
    }
    async update(ctx, next) {
        const { content } = ctx.request.body
        const { momentId } = ctx.params
        const result = await updateMoment(momentId, content)
        ctx.body = result
    }
    async remove(ctx, next) {
        const { momentId } = ctx.params
        const result = await removeMoment(momentId)
        ctx.body = result
    }
    async updateLabel(ctx, next) {
        const { labels } = ctx
        const { momentId } = ctx.params
        // 2.添加所有的标签
        for (let label of labels) {
            // 2.1.判断标签是否已经和动态有关系
            const isExist = await hasLabel(momentId, label.id);
            if (!isExist) {
                await addLabel(momentId, label.id);
            }
        }
        ctx.body = "给动态添加标签成功~"
    }
    async fileInfo(ctx, next) {
        let { filename } = ctx.params
        const { type } = ctx.query
        const file = await getFileByName(filename)
        const types = ["small", "middle", "large"];
        if (types.some(t => t === type)) {
            filename = filename + "-" + type
        }
        ctx.response.set('content-type', file.mimetype);
        ctx.body = fs.createReadStream(`${PICTURE_PATH}/${filename}`);
    }
}
module.exports = new MomentController()